package tt.dz.order.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtill
{

  public static <T> File exportExcel(String title, LinkedHashMap<String, String> fieldMap, List<T> dataset, String fileName)
    throws Exception
  {
    HSSFWorkbook workbook = null;
    File excelFile = new File("/dz/tmp/ms/" + fileName);
    FileOutputStream outputStream = null;
    try
    {
      ensureDirExist("/dz/tmp/ms/");
      if (!excelFile.exists()) {
        excelFile.createNewFile();
      }
      workbook = new HSSFWorkbook();
      
      HSSFSheet sheet = workbook.createSheet(title);
      
      sheet.setDefaultColumnWidth(20);
      
      HSSFCellStyle titleStyle = workbook.createCellStyle();
      
      titleStyle.setFillForegroundColor((short)40);
      titleStyle.setFillPattern((short)1);
      titleStyle.setBorderBottom((short)1);
      titleStyle.setBorderLeft((short)1);
      titleStyle.setBorderRight((short)1);
      titleStyle.setBorderTop((short)1);
      titleStyle.setAlignment((short)2);
      
      HSSFFont font = workbook.createFont();
      font.setColor((short)20);
      font.setFontHeightInPoints((short)12);
      font.setBoldweight((short)700);
      
      titleStyle.setFont(font);
      
      HSSFCellStyle contentStyle = workbook.createCellStyle();
      contentStyle.setFillForegroundColor((short)43);
      contentStyle.setFillPattern((short)1);
      contentStyle.setBorderBottom((short)1);
      contentStyle.setBorderLeft((short)1);
      contentStyle.setBorderRight((short)1);
      contentStyle.setBorderTop((short)1);
      contentStyle.setAlignment((short)2);
      contentStyle.setVerticalAlignment((short)1);
      
      HSSFFont font2 = workbook.createFont();
      font2.setBoldweight((short)400);
      
      contentStyle.setFont(font2);
      

      HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
      
      HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short)6, 5));
      
      comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
      
      comment.setAuthor("leno");
      

      HSSFRow row = sheet.createRow(0);
      Iterator<String> fieldIterator = fieldMap.keySet().iterator();
      int fieldIndex = 0;
      HSSFCell cell;
      while (fieldIterator.hasNext())
      {
        cell = row.createCell(fieldIndex);
        cell.setCellStyle(titleStyle);
        HSSFRichTextString text = new HSSFRichTextString((String)fieldIterator.next());
        cell.setCellValue(text);
        fieldIndex++;
      }
      if (CollectionUtils.isEmpty(dataset)) {
        return excelFile;
      }
      Iterator<T> dataIterator = dataset.iterator();
      int index = 0;
      while (dataIterator.hasNext())
      {
        index++;
        row = sheet.createRow(index);
        Object obj = dataIterator.next();
        fieldIterator = fieldMap.keySet().iterator();
        fieldIndex = 0;
        while (fieldIterator.hasNext())
        {
           cell = row.createCell(fieldIndex);
          cell.setCellStyle(contentStyle);
          String filedEname = (String)fieldMap.get(fieldIterator.next());
          try
          {
            Object value = BeanUtils.getProperty(obj, filedEname);
            String textValue = null;
            if ((value instanceof Date))
            {
              Date date = (Date)value;
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
              textValue = sdf.format(date);
            }
            else
            {
              textValue = value.toString();
            }
            if (textValue != null)
            {
              Pattern p = Pattern.compile("^//d+(//.//d+)?$");
              Matcher matcher = p.matcher(textValue);
              if (matcher.matches())
              {
                cell.setCellValue(Double.parseDouble(textValue));
              }
              else
              {
                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                HSSFFont font3 = workbook.createFont();
                font3.setColor((short)12);
                richString.applyFont(font3);
                cell.setCellValue(richString);
              }
            }
          }
          catch (Exception localException1) {}finally
          {
            fieldIndex++;
          }
        }
      }
      try
      {
        outputStream = new FileOutputStream(excelFile);
        workbook.write(outputStream);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      return excelFile;
    }
    catch (Exception e1)
    {
      if (excelFile.exists()) {
        excelFile.delete();
      }
      throw e1;
    }
    finally
    {
      if (outputStream != null) {
        try
        {
          outputStream.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
      if (workbook != null) {
        try
        {
          workbook.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  public static <T> byte[] getExcelByteArray(String title, LinkedHashMap<String, String> fieldMap, List<T> dataset, String sufferfix)
    throws Exception
  {
    File file = exportExcel(title, fieldMap, dataset, UUID.randomUUID().toString() + sufferfix);
    byte[] bytes = toByteArray(file);
    file.delete();
    
    return bytes;
  }
  
  public static <T> byte[] getXLSByteArray(String title, LinkedHashMap<String, String> fieldMap, List<T> dataset)
    throws Exception
  {
    return getExcelByteArray(title, fieldMap, dataset, ".xls");
  }
  
  public static <T> byte[] getXLSXByteArray(String title, LinkedHashMap<String, String> fieldMap, List<T> dataset)
    throws Exception
  {
    return getExcelByteArray(title, fieldMap, dataset, ".xlsx");
  }
  
  public static <T> byte[] getCSVByteArray(String title, LinkedHashMap<String, String> fieldMap, List<T> dataset)
    throws Exception
  {
    return getExcelByteArray(title, fieldMap, dataset, ".csv");
  }
  
  private static byte[] toByteArray(File file)
    throws IOException
  {
    ByteArrayOutputStream bos = new ByteArrayOutputStream((int)file.length());
    BufferedInputStream in = null;
    try
    {
      in = new BufferedInputStream(new FileInputStream(file));
      int buf_size = 1024;
      byte[] buffer = new byte[buf_size];
      int len = 0;
      while (-1 != (len = in.read(buffer, 0, buf_size))) {
        bos.write(buffer, 0, len);
      }
      return bos.toByteArray();
    }
    catch (IOException e)
    {
      e.printStackTrace();
      throw e;
    }
    finally
    {
      try
      {
        in.close();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
      bos.close();
    }
  }
  
  private static void ensureDirExist(String dir)
  {
    File downLoadDir = new File(dir);
    if (!downLoadDir.exists()) {
      downLoadDir.mkdirs();
    }
  }
  
//  public static void main(String[] args)
//    throws IOException
//  {
//    List<IdentityAccountVO> identityAccountList = new ArrayList();
//    LinkedHashMap<String, String> fieldMap = new LinkedHashMap();
//    fieldMap.put("卡号", "cardNo");
//    fieldMap.put("密码", "password");
//    fieldMap.put("状态", "stateDesc");
//    fieldMap.put("所属企业", "enterpriseName");
//    fieldMap.put("所属运营商", "merchantdesc");
//    File file = new File("d:\\logs\\.csv");
//    if (!file.exists()) {
//      file.createNewFile();
//    }
//    IdentityAccountVO vo = null;
//    for (int i = 0; i < 40000; i++)
//    {
//      vo = new IdentityAccountVO();
//      vo.setCardNo("111111111111");
//      vo.setPassword("aaaaaaaaaaa");
//      vo.setStateDesc("2ddddddd");
//      vo.setEnterpriseName("ddddddddddd");
//      vo.setMerchantdesc("fffffffffffff");
//      identityAccountList.add(vo);
//    }
//    System.out.println("写入文件开始……");
//    long t1 = System.currentTimeMillis();
//
//    System.out.println("使用时间为：" + (System.currentTimeMillis() - t1) + "毫秒");
//  }
}
